package com.gljx.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gljx.constant.Constant;
import com.gljx.shiro.passwordEncrypt.PasswordHelper;
import com.gljx.util.CommonUtil;
import com.gljx.web.dao.HandleMapper;
import com.gljx.web.dao.PowerMapper;
import com.gljx.web.Entity.Handle;
import com.gljx.web.Entity.Power;
import com.gljx.web.Entity.Role;
import com.gljx.web.Entity.User;
import com.gljx.web.service.PowerService;

@Service
@Transactional
public class PowerServiceImpl implements PowerService{

	private  Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private PowerMapper powerDao;
	
	@Autowired
	private HandleMapper handleDao;
	
	@Override
	public List<Map<String, Object>> findAllBIUser(String id,String type) {
		if(type == null || "".equals(type)){
			return powerDao.findAllBIUser(Constant.Project_ID);
		}else{
			//查权限
			if("role".equals(type)){
				return powerDao.findHandleByRoleId(Integer.valueOf(id),
													Constant.Project_ID,"role");
			//用户下的角色和权限
			}else if("user".equals(type)){
				return powerDao.findRoleByUserId(Integer.valueOf(id),Constant.Project_ID);
			}
			return powerDao.findAllBIUser(Constant.Project_ID);
		}
		
	}

	@Override
	public Integer insertRoleByNowUser(String ids, String PID, Integer userId) {
		String[] idStrings = ids.split(",");
		List<Role> roles = new ArrayList<Role>();
		//加入user集合
		for(String string : idStrings){
			Role role = new Role();
			//ID
			role.setId(Integer.valueOf(string));
			roles.add(role);
		}
		return powerDao.insertRoleByNowUser(roles, PID, userId);
	}

	@Override
	public List<Handle> findHandleById(String PID, Integer id,String name) {
		
		return powerDao.findHandleById(PID, id,name);
	}

	@Override
	public Map<String, Object> selectRoleByProject(String rows, 
												   String page, 
												   String id, 
												   String name,
												   String menuName) {
		Integer pageNum = Integer.valueOf(page);
		Integer pageSize = Integer.valueOf(rows);
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("Pindex", pageNum);
		String sql = "select h.ID, h.HANDLE_NAME, h.MENU_ID,"
							+ "h.PROJECTNUMBER, h.HANDLE_URL, h.CREAT_TIME, "
							+ "h.UPDATE_TIME, h.CREAT_ID, h.UPDATE_ID, h.REMARK, "
							+ "h.FIS_DELETE,m.menu_name menuName  "
				   + "from t_e_handle h "
				   		+ "left join t_e_menu m on m.id=h.menu_id "
				   	+ "where h.fis_delete=0 and h.PROJECTNUMBER = '"+Constant.Project_ID+"' ";
	   	if(name != null && !"".equals(name)){
			sql+= " and h.HANDLE_NAME like '%"+name+"%'" ;//操作名
		}
	   	if(menuName != null && !"".equals(menuName)){
			sql+= " and m.menu_name like '%"+menuName+"%'" ;//父菜单名
		}
	   			sql+= "minus "
				   	+ "select h.ID, h.HANDLE_NAME, h.MENU_ID,h.PROJECTNUMBER, "
						   	+ "h.HANDLE_URL,  h.CREAT_TIME, h.UPDATE_TIME, h.CREAT_ID, "
						   	+ "h.UPDATE_ID,  h.REMARK, h.FIS_DELETE,m.menu_name menuName  "
				   	+ "from t_e_handle h  "
				   		+ "inner join t_e_role_handle rh on rh.handle_id = h.id "
				   		+ "left join t_e_menu m on m.id=h.menu_id "
				   	+ "where h.fis_delete=0 and rh.role_id="+Integer.valueOf(id)
				   		+ " and h.PROJECTNUMBER = '"+Constant.Project_ID+"'";
		data.put("Psql",sql);
		data.put("Psize", pageSize);
		handleDao.selectBIMenu(data);
		return data;
	}

	@Override
	public Integer insertHandleByRoleId(String ids, String PID, Integer roleId) {
		String[] idStrings = ids.split(",");
		List<Handle> handles = new ArrayList<Handle>();
		//加入user集合
		for(String string : idStrings){
			Handle handle = new Handle();
			//ID
			handle.setId(Integer.valueOf(string));
			handles.add(handle);
		}
		return powerDao.insertHandleByRoleId(handles, PID, roleId);
	}

	@Override
	public Integer deleteHandleByRoleId(String ids, Integer roleId) {
		String[] idStrings = ids.split(",");
		List<Handle> handles = new ArrayList<Handle>();
		//加入user集合
		for(String string : idStrings){
			Handle handle = new Handle();
			//ID
			handle.setId(Integer.valueOf(string));
			handles.add(handle);
		}
		return powerDao.deleteHandleByRoleId(handles, roleId);
	}

	@Override
	public List<Map<String, Object>> userPowerTree(Integer id, String projectId, String type) {
		
		return null;
	}

	@Override
	public List<Power> findSpowerAndRole(Integer userId, String projectId) {
		return powerDao.findSpowerAndRole(userId, projectId);
	}

	@Override
	public Integer deleteRoleByUserId(String ids, Integer userId) {
		String[] idStrings = ids.split(",");
		List<Role> roles = new ArrayList<Role>();
		//加入user集合
		for(String string : idStrings){
			Role role = new Role();
			//ID
			role.setId(Integer.valueOf(string));
			roles.add(role);
		}
		return powerDao.deleteRoleByUserId(roles, userId);
	}

	@Override
	public Map<String, Object> selectPowerByCon(String rows, String page, 
			String handelName, String pmenuName,
			Integer userId) {
		Integer pageNum = Integer.valueOf(page);
		Integer pageSize = Integer.valueOf(rows);
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("Pindex", pageNum);
		
		String sql=  "select h.handle_name,h.id,m.menu_name menuName,h.HANDLE_URL handleUrl,h.REMARK "
				+ "from t_e_handle h "
				+ "inner join t_e_menu m on m.id=h.menu_id "
				+ "where h.fis_delete = 0 "
				+ "and h.projectnumber='"+Constant.Project_ID+"' ";
		if(handelName != null && !"".equals(handelName)){
			sql+= " and h.HANDLE_NAME like '%"+handelName+"%'" ;//操作名
		}
		if(pmenuName != null && !"".equals(pmenuName)){
			sql+= " and m.MENU_NAME like '%"+pmenuName+"%'" ;//所属菜单
		}
		String bsql = " minus "
				+ "select h.handle_name,h.id,m.menu_name menuName,h.HANDLE_URL handleUrl,h.REMARK  "
				+ "from t_e_handle h "
				+ "inner join t_e_user_handle uh on uh.handle_id=h.id "
				+ "inner join t_e_menu m on m.id=h.menu_id "
				+ "where h.fis_delete = 0 "
				+ "and h.projectnumber='"+Constant.Project_ID+"' "
				+ "and uh.user_id="+userId
				+" minus "
				+ "select h.handle_name,h.id,m.menu_name menuName,h.HANDLE_URL handleUrl,h.REMARK  "
				+ "from t_e_role r "
				+ "inner join t_e_role_user ru on ru.role_id = r.id "
				+ "inner join t_e_role_handle rh on rh.role_id = r.id "
				+ "inner join t_e_handle h on h.id=rh.handle_id "
				+ "inner join t_e_menu m on m.id=h.menu_id "
				+ "where ru.user_id = "+userId
				+ " and h.projectnumber='"+Constant.Project_ID+"' "
				+ "and  h.fis_delete = 0";
		sql +=bsql;
		data.put("Psql",sql);
		data.put("Psize", pageSize);
		
		handleDao.selectBIMenu(data);
		return data;
	}

	@Override
	public Integer insertUserPower(String ids,String PID, Integer userId) {
		String[] idStrings = ids.split(",");
		List<Handle> handles = new ArrayList<Handle>();
		//加入user集合
		for(String string : idStrings){
			Handle handle = new Handle();
			//ID
			handle.setId(Integer.valueOf(string));
			handles.add(handle);
		}
		return powerDao.insertUserPower(handles,PID,userId);
	}

	@Override
	public Integer deleteRoleAndPower(String ids,Integer userId) {
		String[] idStrings = ids.split(",");
		List<Power> powers = new ArrayList<Power>();
		//加入user集合
		for(String string : idStrings){
			Power power = new Power();
			String[] strs = string.split("_");
			//ID
			power.setId(strs[1]);
			power.setType(strs[0]);
			powers.add(power);
		}
		
		return powerDao.deleteRoleAndPower(powers, userId);
	}

	@Override
	public List<Power> findPowerTree(Integer userId, String projectId) {
		List<Power> powertest = powerDao.findPowerTreebyUser(userId, projectId);


		Iterator<Power> powersIT = powertest.iterator();

		int leavelInit = 2;

		List<List<Power>> powersList = new ArrayList<List<Power>>();

		List<Power> chindList = new ArrayList<Power>();

		boolean flag = true;

		//1.将菜单根据 层级拆分成菜单组。
		while(flag) {
			Power m = powersIT.next();
			if(m.getLeavel() != leavelInit)
			{
				leavelInit = m.getLeavel();
				powersList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
			chindList.add(m);
			flag = powersIT.hasNext();
			if(!flag)
			{
				powersList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
		}

		//2.将list组装。

		//倒数第二个数组编号

		for(int lastSize = powersList.size()-2; lastSize >= 0;lastSize--)
		{
			List<Power> outMenus =  powersList.get(lastSize);//将同一层级的菜单组取出

			//下一层级的菜单
			Iterator<Power> menuChid = null;

			//遍历本层级菜单
			for(int i = 0 ;i < outMenus.size();i++)
			{

				//从源获取下一层级菜单
				menuChid = powersList.get(lastSize+1).iterator();

				Power inPower = outMenus.get(i);//本层级菜单

				//菜单类型是父菜单类型才进行判断
				if( !"power".equals(inPower.getType()))
				{
					//System.out.println("集合大小"+memusList.get(lastSize+1).size());

					//循环判别参数
					boolean forFlag = menuChid.hasNext();

					//是否正在进行装载
					boolean nowAdd = false;

					while (forFlag){

						Power power = menuChid.next();//子菜单（下一层级）

						forFlag = menuChid.hasNext();//下一个对象是否存在

						//如果下层级菜单的 父ID == 层级菜单ID
						if((power.get_pid()).equals(inPower.getEasyID()))
						{
							//正在装载
							if(!nowAdd){ nowAdd = true; }

							chindList.add(power);

							menuChid.remove();//删除

							//当没有元素时将数据设置在 本层级的菜单中
							if(!forFlag)
							{
								inPower.setChildren(new ArrayList<>(chindList));
							}
						}
						else if(nowAdd||!forFlag)//正在装载时 或者最后一个对象时 停止循环并装载
						{
							inPower.setChildren(new ArrayList<>(chindList));
							forFlag = false;
						}

					}

					chindList.clear();
				}

			}

		}

		//List<Power> powers = powerDao.findPowerTree(userId, projectId);

		List<Power> resultPower = powersList.get(1);
		Iterator<Power> it = resultPower.iterator();
		int i=5;
		//i = getSize(it,i);
		for(int j = 0 ;j<=i;j++){
			it = resultPower.iterator();
			removeNull(it);
		}


		return resultPower/*powerDao.findPowerTree(userId, projectId)*/;
	}
	
/*	public static <T> List<T> copyIterator(Iterator<T> iter) {  
	    List<T> copy = new ArrayList<T>();  
	    while (iter.hasNext())  
	        copy.add(iter.next());  
	    return copy;  
	}*/
	
	/**
	 * 去空
	* @param it
	* @author LiXiang  @date 2017年11月14日 下午3:36:57
	 */
	public void removeNull(Iterator<Power> it){
		while(it.hasNext()){
			Power p = it.next();
			if(p.getChildren() != null && p.getChildren().size()>0 ){
				Iterator<Power> it2 = p.getChildren().iterator();
				removeNull(it2);
			}else{
				if(!"power".equals(p.getType())){
					it.remove();
				}
			}
		}
	}
	/**
	 * 获取层级
	* @param it
	* @param i
	* @return
	* @author LiXiang  @date 2017年11月14日 下午3:37:05
	 */
	public int getSize(Iterator<Power> it,int i){
		boolean flag =true;
		while(it.hasNext()){
			Power p = it.next();
		    if(p.getChildren().size()>0 && flag){
		    	flag = false;
		    	Iterator<Power> it2 = p.getChildren().iterator();
		    	getSize(it2,++i);
		    }
		}
		return i;
	}

	@Override
	public String InserUsersAddRoles(String userIds, String roleIds) {
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("v_user_id", userIds);
		data.put("v_role_id", roleIds);
		powerDao.InserUsersAddRoles(data);
		return (String) data.get("v_result");
	}
}
